package com.lanou3g.code0416;

import java.io.*;

/**
 * Created by dllo on 18/4/16.
 */
public class Main {
    public static void main(String[] args) {

    }

    public static void copyByBuffer(String srcPath, String desPath) {
        File srcFile = new File(srcPath);
        File desFile = new File(desPath);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            desFile.createNewFile();
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(desFile);
            //BufferedInput/OutputStream创建的时候需要有别的字节流(包装者模式)
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            int pos = 0;
            byte[] buf = new byte[1024];
            while ((pos = bis.read(buf)) != -1) {
                bos.write(buf, 0, pos);
            }
            //在使用BufferedOutputStream的时候,需要在最后加一句bos.flush();冲刷
            //无论bos里的数据满没满都将里面的数据写到硬盘中
            bos.flush();//千万不能写到循环里
            //不写该语句时,在io流关闭时会自动调用该语句,但是可能会在冲刷后丢失数据
            //写此语句,bufered字符流将会和file速度相近,变慢
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //只需要关闭bis和bos
            //会在bis和bos的close方法中自动关闭fis和fos
            //一层套一层,只需要关闭最外面的一层
            IOUtils.closeAll(bis, bos);
        }

    }
}
